import { defineStore } from "pinia";
import { reqLogin, reqUserInfo } from "@/api/user/index";
import type { loginFormData, loginResponseData,userInfoReponseData } from "@/api/user/type";
import type { UserState } from "@/store/modules/type/type";
import router from '@/router'
// 引入路由
import { constantRoute,asyncRoute,anyRoute } from "@/router/routes";
//引入深拷贝方法
// @ts-ignore
import cloneDeep from 'lodash/cloneDeep'
const filterAsyncRoute = (asyncRoute:any,routes:any)=>{
 return asyncRoute.filter((item:any)=>{
    if(routes.includes(item.name)){
      if(item.children&&item.children.length>0){
      item.children = filterAsyncRoute(item.children,routes)
      }
      return true
    }
  })
}
const useUserStore = defineStore("User", {
  state: (): UserState => {
    return {
      token: localStorage.getItem("TOKEN"),
      menuRoutes: constantRoute,
      username: "",
      avatar: "",
      button:[]
    };
  },
  actions: {
    async userLogin(data: loginFormData) {
      let result: loginResponseData = await reqLogin(data);
      if (result.code == 200) {
        this.token = result.data as string;
        localStorage.setItem("TOKEN", this.token);
        return Promise.resolve("ok");
      } else {
        return Promise.reject(new Error(result.data as string));
      }
    },
    async userInfo() {
      let result:userInfoReponseData = await reqUserInfo();
      if (result.code == 200) {
        this.username = result.data.name;
        this.avatar = result.data.avatar;
        this.button = result.data.buttons
        // 计算当前用户需要展示的路由
      let userAsyncRoute = filterAsyncRoute(cloneDeep(asyncRoute),result.data.routes)
      // console.log(userAsyncRoute)
      this.menuRoutes = [...constantRoute,...userAsyncRoute,...anyRoute]
      // 动态添加路由
      let addroute = [...userAsyncRoute,...anyRoute]
      addroute.forEach((item:any)=>{
        router.addRoute(item);
      })
        return 'ok'
      }else{
        return Promise.reject(new Error(result.message));
      }
    },
  },
});
export default useUserStore;
